from django.shortcuts import render
from django.http import HttpResponse
from django.core.paginator import Paginator

from django.shortcuts import redirect
from django.urls import reverse
from django.db.models import Q
from common.models import Goods

from PIL import Image
from datetime import datetime
import time, json, os


def video_index(request, pIndex=1):
    '''浏览信息'''
    # 获取商品信息查询对象
    mod = Goods.objects
    mywhere = []  # 定义一个用于存放搜索条件列表

    # 获取、判断并封装关keyword键搜索
    kw = request.GET.get("keyword", None)
    if kw:
        # 查询商品名中只要含有关键字的都可以
        list1 = mod.filter(Q(goods_name__contains=kw) & Q(typeid=1))
        mywhere.append("keyword=" + kw)
    else:
        list1 = mod.filter(typeid=1)

    # 获取、判断并封装商品状态state搜索条件
    state = request.GET.get('state', '')
    if state != '':
        list1 = list1.filter(state=state)
        mywhere.append("state=" + state)

    # 获取、判断并封装商品状态recommend搜索条件
    recommend = request.GET.get('recommend', '')
    if recommend != '':
        list1 = list1.filter(recommend=recommend)
        mywhere.append("recommend=" + recommend)

    # 执行分页处理
    pIndex = int(pIndex)
    page = Paginator(list1, 12)  # 以12条每页创建分页对象
    maxpages = page.num_pages  # 最大页数
    # 判断页数是否越界
    if pIndex > maxpages:
        pIndex = maxpages
    if pIndex < 1:
        pIndex = 1
    list2 = page.page(pIndex)  # 当前页数据
    plist = page.page_range  # 页码数列表
    px = pIndex
    plist2 = set()
    plist2.add(px)
    for x in range(1, 6):
        if px - x >= 1 and len(plist2) <= 11:
            plist2.add(px - x)
        if px + x <= maxpages and len(plist2) <= 11:
            plist2.add(px + x)

    plist2 = list(plist2)
    plist2.sort()

    context = {"goodslist": list2, 'plist': plist2, 'pIndex': pIndex, 'maxpages': maxpages}

    return render(request, "myadmin/goods/video_index.html", context)


def video_add(request):
    '''加载添加页面'''
    return render(request, "myadmin/goods/video_add.html")


def video_insert(request):
    '''执行添加'''
    try:
        # 判断并执行图片上传，缩放等处理
        myfile = request.FILES.get("pic", None)
        if not myfile:
            return HttpResponse("没有上传文件信息！")
        # 以时间戳命名一个新图片名称
        filename = str(time.time()) + "." + myfile.name.split('.').pop()
        destination = open(os.path.join("./static/goods/", filename), 'wb+')
        for chunk in myfile.chunks():  # 分块写入文件
            destination.write(chunk)
        destination.close()

        # 执行图片缩放
        im = Image.open("./static/goods/" + filename)
        # 缩放到375*375:
        im.thumbnail((375, 375))
        # 把缩放后的图像用jpeg格式保存:
        im.save("./static/goods/" + filename, 'jpeg')
        # 缩放到220*220:
        im.thumbnail((220, 220))
        # 把缩放后的图像用jpeg格式保存:
        im.save("./static/goods/m_" + filename, 'jpeg')
        # 缩放到75*75:
        im.thumbnail((75, 75))
        # 把缩放后的图像用jpeg格式保存:
        im.save("./static/goods/s_" + filename, 'jpeg')

        ob = Goods()
        ob.goods_name = request.POST['goods_name']
        # 判断用户名是否重复
        flag = Goods.objects.filter(goods_name=ob.goods_name)
        if flag:
            context = {"info": "该商品名称已被注册！"}
            return render(request, "myadmin/goods/info.html", context)

        ob.price = int(request.POST['price'])
        ob.content = request.POST['content']
        ob.boughtnum = request.POST['boughtnum']
        ob.clicknum = request.POST['clicknum']
        ob.typeid = 1
        ob.type_name = "视频课程"
        ob.pic_url = filename
        ob.state = 1
        ob.addtime = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        ob.save()
        context = {"info": "添加成功！"}
    except Exception as err:
        print(err)
        context = {"info": "添加失败！"}
    return render(request, "myadmin/goods/info.html", context)


def delete(request, uid):
    '''删除信息'''
    try:
        ob = Goods.objects.get(id=uid)

        os.remove("./static/goods/" + ob.pic_url)
        os.remove("./static/goods/m_" + ob.pic_url)
        os.remove("./static/goods/s_" + ob.pic_url)

        ob.delete()
        context = {"info": "删除成功！"}
    except Exception as err:
        print(err)
        context = {"info": "删除失败！"}
    return render(request, "myadmin/goods/info.html", context)


def video_edit(request, uid):
    '''加载编辑信息页面'''
    try:
        ob = Goods.objects.get(id=uid)
        context = {"goods": ob}
        return render(request, "myadmin/goods/video_edit.html", context)
    except Exception as err:
        print(err)
        context = {"info": "没有找到要修改的信息"}
    return render(request, "myadmin/goods/info.html", context)


def video_update(request, uid):
    '''执行编辑信息'''
    try:
        b = False
        oldpicname = request.POST['oldpicname']
        if None != request.FILES.get("pic"):
            myfile = request.FILES.get("pic", None)
            if not myfile:
                return HttpResponse("没有上传文件信息！")
            # 以时间戳命名一个新图片名称
            filename = str(time.time()) + "." + myfile.name.split('.').pop()
            destination = open(os.path.join("./static/goods/", filename), 'wb+')
            for chunk in myfile.chunks():  # 分块写入文件
                destination.write(chunk)
            destination.close()
            # 执行图片缩放
            im = Image.open("./static/goods/" + filename)
            # 缩放到375*375:
            im.thumbnail((375, 375))
            # 把缩放后的图像用jpeg格式保存:
            im.save("./static/goods/" + filename, 'jpeg')
            # 缩放到220*220:
            im.thumbnail((220, 220))
            # 把缩放后的图像用jpeg格式保存:
            im.save("./static/goods/m_" + filename, 'jpeg')
            # 缩放到75*75:
            im.thumbnail((75, 75))
            # 把缩放后的图像用jpeg格式保存:
            im.save("./static/goods/s_" + filename, 'jpeg')
            b = True
            picname = filename
        else:
            picname = oldpicname
        ob = Goods.objects.get(id=uid)

        ob.price = int(request.POST['price'])
        ob.content = request.POST['content']
        ob.boughtnum = request.POST['boughtnum']
        ob.clicknum = request.POST['clicknum']
        ob.pic_url = picname
        ob.typeid = 1
        ob.type_name = "视频课程"
        ob.state = int(request.POST['state'])
        ob.save()
        context = {"info": "修改成功！"}
        if b:
            os.remove("./static/goods/m_" + oldpicname)  # 执行老图片删除
            os.remove("./static/goods/s_" + oldpicname)  # 执行老图片删除
            os.remove("./static/goods/" + oldpicname)  # 执行老图片删除
    except Exception as err:
        print(err)
        context = {"info": "修改失败！"}
        if b:
            os.remove("./static/goods/m_" + picname)  # 执行新图片删除
            os.remove("./static/goods/s_" + picname)  # 执行新图片删除
            os.remove("./static/goods/" + picname)  # 执行新图片删除
    return render(request, "myadmin/goods/info.html", context)
